package cn.taketoday.live.handler;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.Map;

import cn.taketoday.live.WebSocketMessage;
import cn.taketoday.live.config.GlobalData;
import cn.taketoday.live.config.settings.ThankGiftSetConf;
import cn.taketoday.live.data.Gift;
import cn.taketoday.live.data.Guard;
import cn.taketoday.live.data.enums.ShieldMessage;
import cn.taketoday.live.file.GuardFileTools;
import cn.taketoday.live.http.BilibiliHttpRequests;
import cn.taketoday.live.tools.ParseSetStatusTools;
import cn.taketoday.live.tools.ShieldGiftTools;
import cn.taketoday.live.utils.JodaTimeUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * @author TODAY 2021/5/17 23:06
 */
@Slf4j
public class GuardBuyCommandHandler implements CommandHandler {

  @Override
  public void handle(CommandContext context) throws Exception {
    Guard guard = null;
    Gift gift = null;
    final JSONObject jsonObject = context.getOriginal();
    final StringBuilder stringBuilder = new StringBuilder(32);
    if (context.contains(ShieldMessage.is_gift)) {
      guard = JSONObject.parseObject(jsonObject.getString("data"), Guard.class);
      stringBuilder.append(JodaTimeUtils.formatDateTime(guard.getStart_time() * 1000));
      stringBuilder.append(":有人上船:");
      stringBuilder.append(guard.getUsername());
      stringBuilder.append("在本房间开通了");
      stringBuilder.append(guard.getNum());
      stringBuilder.append("个月");
      stringBuilder.append(guard.getGift_name());
      //控制台打印
      if (context.contains(ShieldMessage.is_cmd)) {
        System.out.println(stringBuilder);
      }
      gift = new Gift();
      gift.setGiftName(guard.getGift_name());
      gift.setNum(guard.getNum());
      gift.setPrice(guard.getPrice());
      gift.setTotal_coin((long) guard.getNum() * guard.getPrice());
      gift.setTimestamp(guard.getStart_time());
      gift.setAction("赠送");
      gift.setCoin_type((short) 1);
      gift.setUname(guard.getUsername());
      gift.setUid(guard.getUid());

      context.sendMessage(WebSocketMessage.of("gift", gift));

      if (GlobalData.logThread != null && !GlobalData.logThread.FLAG) {
        GlobalData.logString.add(stringBuilder.toString());
        synchronized(GlobalData.logThread) {
          GlobalData.logThread.notify();
        }
      }
      stringBuilder.delete(0, stringBuilder.length());
    }
    if (context.contains(ShieldMessage.is_giftThank)) {
      if (GlobalData.parsethankGiftThread != null && !GlobalData.parsethankGiftThread.TFLAG) {
        guard = JSONObject.parseObject(jsonObject.getString("data"), Guard.class);
        gift = new Gift();
        gift.setGiftName(guard.getGift_name());
        gift.setNum(guard.getNum());
        gift.setPrice(guard.getPrice());
        gift.setTotal_coin((long) guard.getNum() * guard.getPrice());
        gift.setTimestamp(guard.getStart_time());
        gift.setAction("赠送");
        gift.setCoin_type((short) 1);
        gift.setUname(guard.getUsername());
        gift.setUid(guard.getUid());

        final MessageHandler messageThread = context.getMessageHandler();

        final ThankGiftSetConf thankGiftSetConf = messageThread.getThankGiftSetConf();
        gift = ShieldGiftTools.shieldGift(gift, ParseSetStatusTools.getGiftShieldStatus(thankGiftSetConf.getShield_status()),
                                          thankGiftSetConf.getGiftStrings(), null);
        if (gift != null) {
          messageThread.parseGiftSetting(gift);
        }
      }
    }
    //开启舰长存放本地
    if (context.contains(ShieldMessage.is_guard_local)) {
      guard = JSONObject.parseObject(jsonObject.getString("data"), Guard.class);
      Map<Long, String> guardHashtable = GuardFileTools.read();
      if (!guardHashtable.containsKey(guard.getUid())) {
        GuardFileTools.write(guard.getUid() + "," + guard.getUsername());
        if (context.contains(ShieldMessage.is_guard_report)) {
          String report = StringUtils.replace(GlobalData.centerSetConf.getThank_gift().getReport(), "\n", "\\n");
          report = StringUtils.replace(report, "%uName%", guard.getUsername());
          //礼品码
          if (context.contains(ShieldMessage.is_giftCode)
                  && !CollectionUtils.isEmpty(GlobalData.centerSetConf.getThank_gift().getCodeStrings())) {
            report = StringUtils.replace(report, "%giftCode%", context.getMessageHandler().sendCode());
          }
          try {
            final MessageHandler messageHandler = context.getMessageHandler();
            if (!StringUtils.isEmpty(messageHandler.getThankGiftSetConf().getReport_barrage().trim())) {
              if (BilibiliHttpRequests.sendMessage(guard.getUid(), report) == 0) {
                final String reportBarrage = messageHandler.getThankGiftSetConf().getReport_barrage();
                BarrageHandler.send(reportBarrage);
              }
            }
            else {
              BilibiliHttpRequests.sendMessage(guard.getUid(), report);
            }
          }
          catch (Exception e) {
            log.error("发送舰长私信失败，原因：" + e);
          }
        }
      }
    }
    else {
      final MessageHandler messageHandler = context.getMessageHandler();
      final ThankGiftSetConf thankGiftSetConf = messageHandler.getThankGiftSetConf();
      if (context.contains(ShieldMessage.is_guard_report)) {
        guard = JSONObject.parseObject(jsonObject.getString("data"), Guard.class);
        String report = StringUtils.replace(thankGiftSetConf.getReport(), "\n", "\\\\r\\\\n");
        report = StringUtils.replace(report, "%uName%", guard.getUsername());
        //礼品码\
        if (context.contains(ShieldMessage.is_giftCode)
                && !CollectionUtils.isEmpty(GlobalData.centerSetConf.getThank_gift().getCodeStrings())) {
          report = StringUtils.replace(report, "%giftCode%", messageHandler.sendCode());
        }
        else {
          report = StringUtils.replace(report, "%giftCode%", "");
        }
        try {
          if (!StringUtils.isEmpty(thankGiftSetConf.getReport_barrage().trim())) {
            if (BilibiliHttpRequests.sendMessage(guard.getUid(), report) == 0) {
              final String reportBarrage = thankGiftSetConf.getReport_barrage();
              BarrageHandler.send(reportBarrage);
            }
          }
          else {
            BilibiliHttpRequests.sendMessage(guard.getUid(), report);
          }
        }
        catch (Exception e) {
          log.error("发送舰长私信失败，原因：" + e);
        }
      }
    }
    // LOGGER.debug("有人上舰长啦:::" + message);
  }

}
